package com.xinlan.imageeditlibrary.editimage.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Arrays;

import com.xinlan.imageeditlibrary.Configs;
import com.xinlan.imageeditlibrary.R;
import com.xinlan.imageeditlibrary.editimage.EditImageActivity;
import com.xinlan.imageeditlibrary.editimage.task.StickerTask;
import com.xinlan.imageeditlibrary.editimage.view.TextStickerView;
import com.xinlan.imageeditlibrary.editimage.view.WheelView;


/**
 * 添加文本贴图
 *
 * @author 潘易
 */
public class AddTextFragment extends Fragment implements TextWatcher {
    public static final int INDEX = 5;
    public static final String TAG = AddTextFragment.class.getName();

    private View mainView;
    private EditImageActivity activity;
    private View backToMenu;// 返回主菜单

    private EditText mInputText;//输入框
    private Button mTextColorSelector,text_type;//颜色选择器
    private TextStickerView mTextStickerView;// 文字贴图显示控件

    private int mTextColor = Color.BLACK;
    private InputMethodManager imm;

    private SaveTextStickerTask mSaveTask;
    
    private boolean select=true;
    
    private AlertDialog dialog;
    private static final String[] PLANETS = new String[]{"系统默认字体"};
    
    public static AddTextFragment newInstance(EditImageActivity activity) {
        AddTextFragment fragment = new AddTextFragment();
        fragment.activity = activity;
        fragment.mTextStickerView = activity.mTextStickerView;
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        mainView = inflater.inflate(R.layout.fragment_edit_image_add_text, null);
        backToMenu = mainView.findViewById(R.id.back_to_main);
        mInputText = (EditText) mainView.findViewById(R.id.text_input);
        mTextColorSelector = (Button) mainView.findViewById(R.id.text_color);
        text_type = (Button) mainView.findViewById(R.id.text_type);
        text_type.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(null!=dialog){
					dialog.show();
				}
			}
		});
        
        if(Configs.isText){
        	mTextColorSelector.setText("黑色文字");
			mTextColorSelector.setTextColor(getResources().getColor(R.color.black));
			mTextColorSelector.setBackgroundResource(R.drawable.circle_shape_white);
			changeTextColor(Color.BLACK);
			select=false;
        }
        
        //颜色选择 按钮点击
        mTextColorSelector.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(select){
					mTextColorSelector.setText("黑色文字");
					mTextColorSelector.setTextColor(getResources().getColor(R.color.black));
					mTextColorSelector.setBackgroundResource(R.drawable.circle_shape_white);
					changeTextColor(Color.BLACK);
					select=false;
				}else{
					mTextColorSelector.setText("白色文字");
					mTextColorSelector.setTextColor(getResources().getColor(R.color.white));
					mTextColorSelector.setBackgroundResource(R.drawable.circle_shape_black);
					changeTextColor(Color.WHITE);
					select=true;
				}
			}
		});
        createDialog();
        return mainView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        backToMenu.setOnClickListener(new BackToMenuClick());// 返回主菜单
        mInputText.addTextChangedListener(this);
        mTextStickerView.setEditText(mInputText);
        changeTextColor(mTextColor);
    }

    @Override
    public void afterTextChanged(Editable s) {
        //mTextStickerView change
        String text = s.toString().trim();
        mTextStickerView.setText(text);
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    /**
     * 修改字体颜色
     *
     * @param newColor
     */
    private void changeTextColor(int newColor) {
        this.mTextColor = newColor;
        mTextStickerView.setTextColor(mTextColor);
    }

    public void hideInput() {
        if (getActivity() != null && getActivity().getCurrentFocus() != null && isInputMethodShow()) {
            imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public boolean isInputMethodShow() {
        return imm.isActive();
    }

    /**
     * 返回按钮逻辑
     *
     * @author panyi
     */
    private final class BackToMenuClick implements OnClickListener {
        @Override
        public void onClick(View v) {
            backToMain();
        }
    }// end class

    /**
     * 返回主菜单
     */
    public void backToMain() {
        hideInput();
        activity.mode = EditImageActivity.MODE_NONE;
        activity.bottomGallery.setCurrentItem(MainMenuFragment.INDEX);
        activity.mainImage.setVisibility(View.VISIBLE);
        activity.updateImageSize();
        activity.bannerFlipper.showPrevious();
        mTextStickerView.setVisibility(View.GONE);
        activity.image_size.setVisibility(View.VISIBLE);
    }

    public void onShow() {
        activity.mode = EditImageActivity.MODE_TEXT;
        activity.bottomGallery.setCurrentItem(AddTextFragment.INDEX);
        activity.mainImage.setImageBitmap(activity.mainBitmap);
        activity.bannerFlipper.showNext();

        activity.image_size.setVisibility(View.GONE);
        mTextStickerView.setVisibility(View.VISIBLE);
        mInputText.clearFocus();
    }

    /**
     * 保存贴图图片
     */
    public void saveTextImage() {
        if (mSaveTask != null) {
            mSaveTask.cancel(true);
        }

        //启动任务
        mSaveTask = new SaveTextStickerTask(activity);
        mSaveTask.execute(activity.mainBitmap);
    }

    private void createDialog(){
    	View outerView = LayoutInflater.from(activity).inflate(R.layout.wheel_view, null);
        WheelView wv = (WheelView) outerView.findViewById(R.id.wheel_view_wv);
        wv.setOffset(2);
        wv.setItems(Arrays.asList(PLANETS));
        wv.setSeletion(3);
        wv.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                System.out.println("selectedIndex: " + selectedIndex + ", item: " + item);
            }
        });
        dialog=new AlertDialog.Builder(activity)
                .setTitle("选择字体")
                .setView(outerView)
                .setPositiveButton("确定", null)
                .create();
    }
    
    
    
    /**
     * 文字合成任务
     * 合成最终图片
     */
    private final class SaveTextStickerTask extends StickerTask {

        public SaveTextStickerTask(EditImageActivity activity) {
            super(activity);
        }

        @Override
        public void handleImage(Canvas canvas, Matrix m) {
            float[] f = new float[9];
            m.getValues(f);
            int dx = (int) f[Matrix.MTRANS_X];
            int dy = (int) f[Matrix.MTRANS_Y];
            float scale_x = f[Matrix.MSCALE_X];
            float scale_y = f[Matrix.MSCALE_Y];
            canvas.save();
            canvas.translate(dx, dy);
            canvas.scale(scale_x, scale_y);
            //System.out.println("scale = " + scale_x + "       " + scale_y + "     " + dx + "    " + dy);
            mTextStickerView.drawText(canvas, mTextStickerView.layout_x,
                    mTextStickerView.layout_y, mTextStickerView.mScale, mTextStickerView.mRotateAngle);
            canvas.restore();
        }

        @Override
        public void onPostResult(Bitmap result) {
            mTextStickerView.clearTextContent();
            mTextStickerView.resetView();
            activity.changeMainBitmap(result);
            backToMain();
        }
    }//end inner class
    
}// end class
